package com.itheima.controller;


import com.itheima.domain.Log;
import com.itheima.domain.User;
import com.itheima.service.LogService;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

@Component
@Aspect
public class LogAop {

    @Autowired
    private HttpServletRequest request;
        @Autowired
        private  LogService logService;

    @Around("execution(* com.itheima.controller.*.*(..))")
    public Object around(ProceedingJoinPoint pjp) throws Throwable {

        Date start = new Date();
        //目标方法执行
        Object proceed = pjp.proceed();
        int time = (int)(new Date().getTime() - start.getTime());
        //获取路径类名
        String className = pjp.getTarget().getClass().getName();
        //获取方法名称
        String methodName = pjp.getSignature().getName();

        User user = (User) request.getSession().getAttribute("user");
        String name=null;
        if(user!=null){
            name=user.getName();
        }else {
            name=request.getParameter("name")+"[登录失败]";
        }

        Log log=new Log();
        log.setName(name);
        log.setTime(new Date());
        log.setUrl("[类名]"+className+"[方法名]"+methodName);
        log.setCost(time);

        logService.save(log);
        return proceed;
    }
}
